package nickthissen.iracing.activities;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import nickthissen.iracing.adapters.FavoriteThreadListAdapter;
import nickthissen.iracing.common.*;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.datamodels.FavThreadsResult;
import nickthissen.iracing.datamodels.FavoriteThread;
import nickthissen.iracing.datamodels.ForumList;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.datamodels.Thread;
import nickthissen.iracing.datamodels.User;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;

public class FavoriteThreadsActivity extends TaskItemListActivity<FavoriteThread>
{
    private ArrayList<FavoriteThread> favorites;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorites);

        this.loadFavorites();

        this.getSupportActionBar().setTitle("Favorite threads");
	}

    public static Intent getIntent(Context context)
    {
        Intent i = new Intent(context, FavoriteThreadsActivity.class);
        return i;
    }

    private void loadFavorites()
    {
        this.startLoading("Loading favorites...", null, false);
    }

    @Override
    protected Task<?> createTask()
    {
        return new Task<Void>(this, loader);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {
    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return null;
    }
	
	@Override
	protected void setItems(ArrayList<FavoriteThread> items) 
	{
        FavoriteThreadListAdapter adapter = new FavoriteThreadListAdapter(this, R.layout.favoriterow, items);
        this.setListAdapter(adapter);
    }

	@Override
	public void onItemClicked(FavoriteThread item) 
	{
        this.openThread(item, false);
	}

	public boolean deleteFavorite(FavoriteThread thread) 
	{
        DialogClickListener clickListener = new DialogClickListener(this, thread);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to remove this thread from your favorites?")
                .setPositiveButton("Yes", clickListener)
                .setNegativeButton("No", clickListener)
                .show();
        return true;
	}

    private class DialogClickListener implements DialogInterface.OnClickListener
    {
        Activity context;
        FavoriteThread thread;

        public DialogClickListener(Activity context, FavoriteThread thread)
        {
            this.context = context;
            this.thread = thread;
        }

        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            if (which == DialogInterface.BUTTON_POSITIVE)
            {
                favorites.remove(thread);
                setItems(favorites);

                new Task<FavoriteThread>(context, new DataLoader<FavoriteThread>()
                {
                    @Override
                    public Result getData(FavoriteThread in)
                    {
                        return Networking.deleteFavorite(this.getContext(), User.currentUser, in);
                    }

                    @Override
                    public void onFinished(Result out)
                    {
                        if (out.Success)
                        {
                            Toast.makeText(context, "Favorite deleted.", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Error.fromResult(out).report(this.getContext());
                        }
                    }
                }).execute(thread);
            }
            dialog.dismiss();
        }
    }

    public void onLastPageButtonClicked(FavoriteThread thread)
    {
        this.openThread(thread, true);
    }

    private void openThread(FavoriteThread favThread, boolean lastPage)
    {
        Thread thread = new Thread();
        thread.Id = favThread.ThreadId;
        thread.Title = favThread.ThreadName;
        thread.Url = favThread.ThreadUrl;

        Intent intent = ThreadActivity.getIntent(this, thread, favThread.ForumId, lastPage);
        this.startActivityForResult(intent, 0);
    }

    @Override
	protected void loadData() {
		// TODO Auto-generated method stub
		
	}

    private DataLoader<Void> loader = new DataLoader<Void>()
    {
        @Override
        public Result getData(Void in)
        {
            FavThreadsResult result = Networking.getFavorites(this.getContext(), User.currentUser);
            if (result != null && result.Success)
            {
                return Result.ok(result.Object);
            }
            return Result.failed();
        }

        @Override
        public void onFinished(Result out)
        {
            if (out == null) out = Result.failed();

            favorites = new ArrayList<FavoriteThread>();
            if (out.Success)
            {
                if (out.Object != null)
                {
                    favorites.addAll((ArrayList<FavoriteThread>)out.Object);
                    for (FavoriteThread fav : favorites)
                    {
                        fav.Username = User.currentUser.username;
                    }
                }
            }
            else
            {
                Error.fromResult(out).report(this.getContext());
            }

            setItems(favorites);

            finishedLoading();
        }
    };
}
